#include "timinterruptinit.h"
#include "debug.h"
#include "ledflashmode.h"

uint16_t interruptTime = 0;

void TIM2_IRQHandler(void) __attribute__((interrupt("WCH-Interrupt-fast")));

void TimInterruptInit(uint16_t arr,uint16_t psc)
{
    TIM_interruptTimeBaseInitTypeDef TIM_interruptTimeBaseInitStructure;
    NVIC_InitTypeDef        NVIC_InitStructure;

    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);

    TIM_interruptTimeBaseInitStructure.TIM_Period = arr;
    TIM_interruptTimeBaseInitStructure.TIM_Prescaler = psc;
    TIM_interruptTimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_interruptTimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_interruptTimeBaseInit(TIM1, &TIM_interruptTimeBaseInitStructure);

    TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);

    NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);

    TIM_Cmd(TIM2, ENABLE);
}

void TIM2_IRQHandler(void)
{
    if (TIM_GetITStatus(TIM2, TIM_IT_Update) == SET) {
        interruptTime++;

        if (interruptTime == 5000) {
            LedModeChange();
            interruptTime = 0;
        }

        TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
    }
}
